package com.dts.controller;

import com.dts.dto.UserDto;
import com.dts.entity.User;
import com.dts.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(UserDto user, HttpServletRequest request) {
        User login = userService.login(user);
        //lsjfljs
        if (login != null) {
            request.getSession().setAttribute("user", login);
            return "redirect:/index.jsp";
        }
        return "/login";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return "redirect:/login.jsp";
    }

    @RequestMapping("/register")
    public String register(@RequestParam("name") String name,
                           @RequestParam("password") String password,
                           @RequestParam("file") MultipartFile file,
                           Model model) throws IOException {
        UserDto user = new UserDto(name,password);
        boolean flag = userService.findByName(user.getName());
        if (flag) {
            model.addAttribute("msg", "用户名已存在");
            return "/register";
        }
        String jpg = "photo_"+System.currentTimeMillis() +"."+ file.getOriginalFilename().split("\\.")[1];
        String filePath ="D:\\cxdownload\\" +jpg;
        file.transferTo(new File(filePath));
        user.setPhoto(jpg);
        userService.regiser(user);
        return "redirect:/login.jsp";
    }


}
